package com.insight.config;

import com.insight.common.mq.stream.Streams;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池任务配置类，定义了多种业务场景下的线程池Bean。
 * 包括流处理、定时任务、工单处理、报表等线程池。
 */
@EnableAsync(proxyTargetClass = true)
@Configuration
public class ThreadPoolTaskConfig {
    /**
     * 流处理核心线程池
     * @return 线程池执行器
     */
    @Bean(value = "stream-core-pool")
    public ThreadPoolExecutor streamCorePool() {
        AtomicInteger index = new AtomicInteger(1);
        return new ThreadPoolExecutor(Streams.values().length * 4, Streams.values().length * 8, 0, TimeUnit.DAYS,
                new LinkedBlockingDeque<>(), r -> {
            Thread thread = new Thread(r);
            thread.setName("async-stream-consumer-" + index.getAndIncrement());
            thread.setDaemon(true);
            return thread;
        });
    }

    /**
     * quartz定时任务核心线程池
     * @return 线程池执行器
     */
    @Bean(value = "quartz-core-pool")
    public ThreadPoolExecutor quartzCorePool() {
        AtomicInteger index = new AtomicInteger(1);
        return new ThreadPoolExecutor(16, 100, 60, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(), r -> {
            Thread thread = new Thread(r);
            thread.setName("async-quartz-thread-" + index.getAndIncrement());
            //thread.setDaemon(true);
            return thread;
        });
    }

    /**
     * 工单处理线程池
     * @return 线程池执行器
     */
    @Bean(value = "issue-task-pool")
    public ThreadPoolExecutor issueTaskPool() {
        AtomicInteger index = new AtomicInteger(1);
        return new ThreadPoolExecutor(100, 400, 60, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(), r -> {
            Thread thread = new Thread(r);
            thread.setName("issue-task-pool-" + index.getAndIncrement());
            //thread.setDaemon(true);
            return thread;
        });
    }

    /**
     * 报表处理线程池
     * @return 线程池执行器
     */
    @Bean(value = "report-core-pool")
    public ThreadPoolExecutor reportCorePool() {
        AtomicInteger index = new AtomicInteger(1);
        return new ThreadPoolExecutor(200, 400, 60, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(), r -> {
            Thread thread = new Thread(r);
            thread.setName("async-report-thread-" + index.getAndIncrement());
            //thread.setDaemon(true);
            return thread;
        });
    }

}
